package com.njupt.yanglonglong.report.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njupt.yanglonglong.report.demo.common.Result;
import com.njupt.yanglonglong.report.demo.entity.RUser;
import com.njupt.yanglonglong.report.demo.mapper.UserMapper;
import com.njupt.yanglonglong.report.demo.utils.JwtUtil;
import com.njupt.yanglonglong.report.demo.utils.MD5EncodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @Author yangllong
 * @Date 2021/4/1 18:35
 */
@RestController
@Slf4j
@CrossOrigin
public class LoginController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public JSONObject login(@RequestBody JSONObject jsonObject) {
        JSONObject res = new JSONObject();
        JSONObject data = new JSONObject();
        JSONObject meta = new JSONObject();
        QueryWrapper<RUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", jsonObject.getString("username"));
        wrapper.eq("user_type", jsonObject.getString("usertype"));
        RUser user = userMapper.selectOne(wrapper);
        if (user == null) {
            meta.put("msg", "用户不存在或用户类型有误");
            meta.put("status", "500");
            res.put("data", data);
            res.put("meta", meta);
            return res;
        }
        String pwd = MD5EncodeUtil.getMD5Code(jsonObject.getString("password"));
        if (user.getPassword().equals(pwd)) {
            String token = JwtUtil.createToken(user);
            log.info(user.getUsername() + "登陆成功");
            log.info("[ 已生成token: ]" + token);
            // token user信息存入redis中，保存30min
            try {
                redisTemplate.opsForValue().set(token, user, Duration.ofMinutes(30L));
                log.info("[ 用户信息存入token ]");
            } catch (Exception e) {
                log.error("[ redis exception ]:" + e);
            }
            data.put("username", user.getUsername());
            data.put("userid", user.getUserId());
            data.put("usertype", user.getUserType());
            data.put("token", token);
            meta.put("msg", "登陆成功，欢迎您" + user.getUsername());
            meta.put("status", "200");
        } else {
            meta.put("msg", "用户名或密码错误");
            meta.put("status", "500");
        }
        res.put("data", data);
        res.put("meta", meta);
        return res;
    }

    @PostMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Object user = redisTemplate.opsForValue().get(token);
        try {
            redisTemplate.expire(token, 30, TimeUnit.MINUTES);
            log.info("重置token时间成功");
        } catch (Exception e) {
            log.error("重置token时间出错" + e);
        }
        if (user == null) {
            log.info("获取用户信息失败");
            return Result.unauthorized();
        }
        return Result.success(user);
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Boolean delete = redisTemplate.delete(token);
        if (!delete) {
            log.info("redis中不存在token");
            return Result.error("用户不存在");
        }
        log.info("清除token成功");
        return Result.success();
    }
}
